//
//  ShareFacebook.m
//  FB_skd
//
//  Created by Le Thanh Hai on 4/20/13.
//  Copyright (c) 2013 Le Thanh Hai. All rights reserved.
//

#import "ShareFacebook.h"
#import "Global.h"

@interface FacebookConnect()
@property (nonatomic, copy) FBHandler fbHandler;
@property (nonatomic, copy) FBError   fbError;
@end

@implementation FacebookConnect
@synthesize fbHandler, fbError;

- (FBRequest*)requestWithGraphPath:(NSString *)graphPath
                         andParams:(NSMutableDictionary *)params
                     andHttpMethod:(NSString *)httpMethod
                         FBHandler:(FBHandler)data
                           fbError:(FBError)error
{
    self.fbHandler = data;
    self.fbError = error;
    [appDelegate showBusyView:YES];
    return [self requestWithGraphPath:graphPath andParams:params andHttpMethod:httpMethod andDelegate:self];
}


- (void)request:(FBRequest *)request didReceiveResponse:(NSURLResponse *)response
{

}

- (void)request:(FBRequest *)request didFailWithError:(NSError *)error
{
    [appDelegate showBusyView:NO];
    if (self.fbError) {
        self.fbError(error);
    }
}

- (void)request:(FBRequest *)request didLoadRawResponse:(NSData *)data
{
    [appDelegate showBusyView:NO];
    if (self.fbHandler) {
        self.fbHandler(data);
    }
}

- (void)dealloc
{
    NSLog(@"%s", __func__);
    [super dealloc];
}
@end

@interface ShareFacebook()

@end

static ShareFacebook *sharedInstance = nil;

@implementation ShareFacebook
@synthesize delegate;
@synthesize facebook;
@synthesize permissions;
@synthesize handler;
@synthesize fbHandler;

+(id)shareInstance
{
    if (!sharedInstance) {
        sharedInstance = [[ShareFacebook alloc] init];
    }
    return sharedInstance;
}

+(BOOL)canUseFacebook
{
    return ([Global checkNetworkAvailable] && [[sharedInstance facebook] isSessionValid]);
}

-(id)init
{
    if (self = [super init]) {
        NSString *facebook_id = [[FBSession activeSession] appID];
        facebook = [[FacebookConnect alloc] initWithAppId:facebook_id andDelegate:self];

        
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        if ([defaults objectForKey:kFBRankingAccessToken]) {
            facebook.accessToken = [defaults objectForKey:kFBRankingAccessToken];
        }
        if ([defaults objectForKey:kFBRankingExpirationDate]) {
            facebook.expirationDate = [defaults objectForKey:kFBRankingExpirationDate];
        }

    }
    return self;
}

-(BOOL)statusLogin
{
    return [facebook isSessionValid];
}

-(void)authorize
{
    [facebook authorize: permissions];
}

#pragma mark -- delegate facebook
- (void)fbDidLogin
{
    [self storeAuthData:facebook.accessToken expiresAt:facebook.expirationDate];
    if (delegate != nil && [delegate respondsToSelector:@selector(fbDidLogin)]) {
        [delegate fbDidLogin];
    }
}

-(void)fbSessionInvalidated
{
    NSLog(@"%s", __func__);
}

- (void)fbDidLogout
{
    NSLog(@"%s", __func__);
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults removeObjectForKey:kFBRankingAccessToken];
    [defaults removeObjectForKey:kFBRankingExpirationDate];
    [defaults synchronize];
}

-(void)fbDidNotLogin:(BOOL)cancelled
{
    NSLog(@"%s", __func__);
}

- (void)fbDidExtendToken:(NSString *)accessToken expiresAt:(NSDate *)expiresAt
{
    NSLog(@"%s", __func__);
    [self storeAuthData:facebook.accessToken expiresAt:facebook.expirationDate];
}

- (void)storeAuthData:(NSString *)accessToken expiresAt:(NSDate *)expiresAt {
    NSLog(@"accessToken = %@", accessToken);
    NSLog(@"expiresAt = %@", [expiresAt description]);
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:accessToken forKey:kFBRankingAccessToken];
    [defaults setObject:expiresAt forKey:kFBRankingExpirationDate];
    [defaults synchronize];
}

#pragma mark -- for game
-(void)postScore:(int)score complete:(HandleEvent)handler_
{
   self.handler = handler_;
    NSMutableDictionary* params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:@"%d", score], @"score", nil];
    
    [facebook requestWithGraphPath:@"me/scores" andParams:nil andHttpMethod:@"GET" FBHandler:^(id data) {
        NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSDictionary *dic = [[[SBJSON alloc] init] objectWithString:jsonString];
        if ([[dic allKeys] containsObject:@"data"]) {
            NSLog(@"Fetching current score %@", [dic description]);
            if ([[dic objectForKey:@"data"] count] == 0) {
                // post new hight score
                [facebook requestWithGraphPath:@"me/scores" andParams:params andHttpMethod:@"POST" FBHandler:^(id data) {
                    NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                    if ([jsonString isEqualToString:@"true"]) {
                        NSLog(@"update new score");
                    } else {
                        NSLog(@"error %@", jsonString);
                    }
                    if (self.handler) {
                        self.handler();
                    }
                } fbError:nil];
                return;
            }
            
            int currentScore = [[[[dic objectForKey:@"data"] objectAtIndex:0] objectForKey:@"score"] intValue];
            NSLog(@"currentScore = %d", currentScore);

            if (score > currentScore) {
                // post new hight score
                [facebook requestWithGraphPath:@"me/scores" andParams:params andHttpMethod:@"POST" FBHandler:^(id data) {
                    NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                    if ([jsonString isEqualToString:@"true"]) {
                        NSLog(@"update new score");
                        if (self.handler) {
                            self.handler();
                        }
                    } else {
                        if (self.handler) {
                            self.handler();
                        }
                    }
                } fbError:nil];
            } else {
                if (self.handler) {
                    self.handler();
                }
            }
        }
    } fbError:^(id data) {
        NSLog(@"%@", [data description]);
        
    }];
}

#pragma mark -- private function
- (void)getRankingList:(FBHandler)handler_
{
    self.fbHandler = handler_;
    [facebook requestWithGraphPath:[NSString stringWithFormat:@"%@/scores?fields=score", [[FBSession activeSession] appID]] andParams:nil andHttpMethod:@"GET" FBHandler:^(id data) {
        NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSDictionary *dic = [[[SBJSON alloc] init] objectWithString:jsonString];
        if ([[dic allKeys] containsObject:@"data"]) {
            if (self.fbHandler) {
                self.fbHandler([dic objectForKey:@"data"]);
            }
        }
    } fbError:nil];
}

-(void)getAllFriend:(FBHandler)handler_
{
    self.handler = handler_;
    [facebook requestWithGraphPath:@"me?fields=friends.fields(installed,id,name)" andParams:nil andHttpMethod:@"GET" FBHandler:^(id data) {
        NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSDictionary *dic = [[[SBJSON alloc] init] objectWithString:jsonString];
        if ([[dic allKeys] containsObject:@"friends"]) {
            if (self.handler) {
                self.handler([[dic objectForKey:@"friends"] objectForKey:@"data"]);
            }
        }
    } fbError:nil];
}
@end
